package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.constants.ArticleConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.joda.time.DateTime;
import org.junit.runner.Computer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IWemediaClient wemediaClient;
    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {

        //1.查询前五天的文章
        //1.1获取五天前的时间
        Date date = DateTime.now().minusDays(50).toDate();
        //1.2调用方法获取五天内文章
        List<ApArticle> last5Article = articleMapper.findArticleListByLast5days(date);

        //2.计算文章的分值
        List<HotArticleVo> hotArticleVoList = computerArticle(last5Article);

        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 为每个频道缓存30条分值较高的文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //1.远程调用feign接口,获取频道列表
        ResponseResult response = wemediaClient.getHotChannels();
        if (response.getCode().equals(200)){
            //序列化数据
            String jsonString = JSON.toJSONString(response.getData());
            //转换成封装WmChannels对象的List集合
            List<WmChannel> wmChannels = JSON.parseArray(jsonString, WmChannel.class);
            //参数校验
            if (wmChannels.size()>0 && wmChannels != null){
                for (WmChannel wmChannel : wmChannels) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(x -> x.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());
//                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(hotArticleVo -> hotArticleVo.getChannelId().equals(wmChannel.getId())).distinct().collect(Collectors.toList());
                    //取分值高的30条数据,并存入redis中
                    sortAndCache(hotArticleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId());
                }
            }

            //推荐数据
            sortAndCache(hotArticleVoList,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
        }
    }

    /**
     * 取分值高的30条数据,并存入redis中
     * @param hotArticleVos
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (hotArticleVos.size() > 30){
            hotArticleVos = hotArticleVos.subList(0, 30);
        }
        cacheService.set(key,JSON.toJSONString(hotArticleVos));
    }




    /**
     * 计算文章分值
     * @param last5Article
     * @return
     */
    private List<HotArticleVo> computerArticle(List<ApArticle> last5Article) {

        List<HotArticleVo> hotArticleVoList = new ArrayList<>();

        if (last5Article.size()>0 && last5Article != null){
            for (ApArticle apArticle : last5Article) {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(apArticle,hot);
                //封装方法进行具体的分数计算
                Integer score = computerScore(hot);
                hot.setScore(score);
                hotArticleVoList.add(hot);
            }
        }

        return hotArticleVoList;
    }

    //分值具体计算
    private Integer computerScore(HotArticleVo hot) {
        int score = 0;
        if (hot.getLikes()!=null){
            score += hot.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (hot.getViews() != null){
            score += hot.getViews();
        }
        if (hot.getComment()!=null){
            score += hot.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (hot.getCollection() != null){
            score += hot.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
